package com.blockchain.securewallet.activities;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.blockchain.securewallet.R;
import com.blockchain.securewallet.WalletApp;
import com.blockchain.securewallet.base.BaseActivity;
import com.blockchain.securewallet.dialog.BottomSlide;
import com.blockchain.securewallet.dialog.IDialogListener;
import com.blockchain.securewallet.dialog.UniversalDialog;
import com.blockchain.securewallet.manager.ThreadPoolManager;
import com.blockchain.securewallet.model.db.BlockAddress;
import com.blockchain.securewallet.model.db.dao.BlockAddressDao;
import com.blockchain.securewallet.tools.WeakHandler;
import com.blockchain.securewallet.utils.Logger;
import com.blockchain.securewallet.utils.StringUtil;
import com.blockchain.securewallet.utils.ToastUtils;
import com.blockchain.securewallet.utils.ToolUtils;
import com.blockchain.securewallet.utils.UIHelper;
import com.blockchain.securewallet.view.SelectorButton;

import java.lang.ref.WeakReference;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bingoogolapple.qrcode.core.BGAQRCodeUtil;
import cn.bingoogolapple.qrcode.zxing.QRCodeEncoder;

public class AddressInfoActivity extends BaseActivity implements View.OnTouchListener, IDialogListener {

    public static final String KEY_ADDRESS_TYPE = "address_type";
    public static final String KEY_ADDRESS_CONTENT = "address_content";
    public static final String KEY_ADDRESS_NOTE = "address_note";

    @BindView(R.id.edit_address)
    EditText editAddress;

    @BindView(R.id.edit_class)
    EditText editAddressClass;

    @BindView(R.id.tv_class_label)
    TextView tvAddressClass;

    @BindView(R.id.edit_name)
    EditText editAddressNote;

    @BindView(R.id.tv_title)
    TextView tvTitle;

    @BindView(R.id.qr_address)
    ImageView addrQrCode;

    @BindView(R.id.btn_update)
    SelectorButton sbUpdate;

    private String address = "";
    private String addressNote = "";
    private String addressClass = "";
    private int type = 0;
    //private AsyncTask<Void, Void, Bitmap> task;
    private boolean isInterrupt = true;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address_info);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        if (intent != null) {
            int type = intent.getIntExtra(KEY_ADDRESS_TYPE, BlockAddress.TYPE_BIT_CON);
            if (type == BlockAddress.TYPE_BIT_CON) {
                addressClass = getString(R.string.bit_coin_name);
                editAddressClass.setText(addressClass);
            } else {
                addressClass = getString(R.string.eth_coin_name);
                editAddressClass.setText(R.string.eth_coin_name);
            }

            address = intent.getStringExtra(KEY_ADDRESS_CONTENT);
            addressNote = intent.getStringExtra(KEY_ADDRESS_NOTE);
            editAddress.setText(address);
            editAddressNote.setText(addressNote);
        }

        tvTitle.setText(R.string.address_info);

        UIHelper.expandViewTouchDelegate(sbUpdate, 40, 40, 80, 80);

        tvAddressClass.setOnTouchListener(this);
        editAddressClass.setOnTouchListener(this);

        //生成地址二维码
        generateQrCode(address, addrQrCode);
    }

    @OnClick(R.id.btn_back)
    void back() {
        finish();
    }


    //生成地址二维码并进行内存泄漏处理
    private void generateQrCode(final String address, ImageView addrQrCode) {
        new MyTask(this, address, addrQrCode).execute();

        /*task = new AsyncTask<Void, Void, Bitmap>() {
            @Override
            protected Bitmap doInBackground(Void... voids) {
                return null;
            }
        };
        task.execute();*/
    }


    @Override
    public boolean onTouch(View v, MotionEvent event) {
        //使得相应控件点击(获取焦点)一次即可调用其点击事件
        if (event.getAction() == MotionEvent.ACTION_UP) {
            v.performClick();
        }
        //如为false，执行ACTION_DOWN后不再往下执行
        return true;
    }


    @Override
    public void onItemClick(String... texts) {
        //String[] texts
        //执行删除操作

        try {

            ThreadPoolManager.execute(new Runnable() {
                @Override
                public void run() {
                    Logger.ds("正在执行删除");

                    //WalletApp.getInstance().getDaoSession().getBlockAddressDao().update(address);
                    List<BlockAddress> addresses = WalletApp.getInstance().getDaoSession().loadAll(BlockAddress.class);
                    BlockAddressDao addressDao = WalletApp.getInstance().getDaoSession().getBlockAddressDao();

                    for (int i = 0; i < addresses.size(); i++) {
                        BlockAddress bean = addresses.get(i);
                        Logger.d("\n" + bean.toString() + "\n");

                        if (bean.getAddress().equals(address)) {
                            //BlockAddress entity = new BlockAddress();
                            //entity.setId(bean.getId());
                            /*entity.setType(type);
                            entity.setNote(note);
                            entity.setAddress(location);*/
                            Logger.ds(bean.getId() + ":\tdelete BlockAddress where Id == " + bean.getId());
                            //addressDao.delete(entity);
                            addressDao.deleteByKey(bean.getId());
                            break;
                        }
                    }

                    Logger.ds("try-地址：删除完毕");
                    handler.sendEmptyMessage(1);
                }
            });

        } catch (Exception e) {
            Logger.ds("> catch-删除地址: " + e.getMessage());
        } finally {
            //这里需要注意，try-catch-finally体系中，finally不会等待try中的子线程执行完
            Logger.ds("finally delete");
        }

        finish();
    }


    static class MyTask extends AsyncTask<Void, Void, Bitmap> {

        String address;
        WeakReference<Activity> weakReference;
        WeakReference<ImageView> ivWeakReference;

        MyTask(Activity activity, String address, ImageView addrQrCode) {
            this.address = address;
            weakReference = new WeakReference<>(activity);
            ivWeakReference = new WeakReference<>(addrQrCode);
        }

        @Override
        protected Bitmap doInBackground(Void... voids) {
            return QRCodeEncoder.syncEncodeQRCode(address, BGAQRCodeUtil.dp2px(weakReference.get(), 150));
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            Activity activity = weakReference.get();
            if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
                return;
            }

            if (bitmap != null) {
                ivWeakReference.get().setImageBitmap(bitmap);
                ivWeakReference.get().setVisibility(View.VISIBLE);
            } else {
                Toast.makeText(activity, "生成二维码失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //加了这个，task区块还是会变黄啊
        //task.cancel(true);
    }


    @OnClick(R.id.iv_delete)
    void deleteAddress() {
        //ToastUtils.showToast("点击弹出个确认是否删除当前地址项的弹窗");

        String title = StringUtil.getResourceString(R.string.address_book_delete_title);
        String content = StringUtil.getResourceString(R.string.address_book_delete_content);
        UniversalDialog.showSingeleTipDialog(getSupportFragmentManager(), this, title, content);
    }


    @OnClick(R.id.iv_edit)
    void editAddress() {
        //如果拦截了，就开启
        if (isInterrupt) {
            //开启可编辑模式
            editAddressNote.requestFocus();
            editAddressNote.setEnabled(true);
            editAddress.setEnabled(true);
            sbUpdate.setVisibility(View.VISIBLE);
            isInterrupt = false;
            return;
        }

        //没有拦截（就表示已经开启的意思）
        //则，关闭可编辑模式
        editAddressNote.setEnabled(false);
        editAddress.setEnabled(false);
        sbUpdate.setVisibility(View.GONE);
        isInterrupt = true;

        if (!editAddress.getText().toString().equals(address)) {
            editAddress.setText(address);
        }
        if (!editAddressNote.getText().toString().equals(addressNote)) {
            editAddressNote.setText(addressNote);
        }
        if (!editAddressClass.getText().toString().equals(addressClass)) {
            editAddressClass.setText(addressClass);
        }
    }


    @OnClick({R.id.edit_class, R.id.tv_class_label})
    void editCoinType() {
        if (isInterrupt) return;

        BottomSlide dialog = BottomSlide.newInstance("", new String[]{getString(R.string.cn_btc), getString(R.string.cn_eth)});
        dialog.show(getSupportFragmentManager(), "dialog");
        //add item click listener
        dialog.setListener(new BottomSlide.OnClickListener() {
            @Override
            public void click(int position) {
                if (position == 0) {
                    type = BlockAddress.TYPE_BIT_CON;
                    editAddressClass.setText(getString(R.string.cn_btc));
                } else {
                    type = BlockAddress.TYPE_ETH_COIN;
                    editAddressClass.setText(getString(R.string.cn_eth));
                }
            }
        });
    }


    @OnClick(R.id.btn_update)
    void updateAddress() {

        final String location = editAddress.getText().toString();
        if (StringUtil.isEmpty(location.trim())) {
            ToastUtils.showToast("地址不能为空");
            return;
        }

        final String note = editAddressNote.getText().toString();
        if (StringUtil.isEmpty(note.trim())) {
            //去掉空格后也不能为空
            ToastUtils.showToast("名称备注不能为空");
            return;
        }

        if (note.trim().length() > 10) {
            //名称备注不能超过10位
            ToastUtils.showToast("名称备注不能超过10位");
            return;
        }
        
        //不是正确的地址
        if (!ToolUtils.isCorrectAddress(location.trim())) {
            //地址格式不正确
            ToastUtils.showToast("地址格式不正确");
            return;
        }
        

        try {

            ThreadPoolManager.execute(new Runnable() {
                @Override
                public void run() {
                    Logger.ds("正在执行更新");

                    //WalletApp.getInstance().getDaoSession().getBlockAddressDao().update(address);
                    List<BlockAddress> addresses = WalletApp.getInstance().getDaoSession().loadAll(BlockAddress.class);
                    BlockAddressDao addressDao = WalletApp.getInstance().getDaoSession().getBlockAddressDao();

                    for (int i = 0; i < addresses.size(); i++) {
                        BlockAddress bean = addresses.get(i);
                        Logger.d("\n" + bean.toString() + "\n");

                        if (bean.getAddress().equals(address)) {
                            BlockAddress entity = new BlockAddress();
                            entity.setId(bean.getId());
                            entity.setType(type);
                            entity.setNote(note);
                            entity.setAddress(location);
                            Logger.ds(bean.getId() + ":\tupdate BlockAddress set type = " + type + "  where type == -1");
                            addressDao.update(entity);
                            break;
                        }
                    }

                    Logger.ds("try-地址：更新完毕");
                    handler.sendEmptyMessage(0);
                }
            });

        } catch (Exception e) {
            Logger.ds("> catch-修改地址: " + e.getMessage());
        } finally {
            //这里需要注意，try-catch-finally体系中，finally不会等待try中的子线程执行完
            Logger.ds("finally update");
        }

        finish();
    }


    //避免内存泄漏的Handler的使用
    WeakHandler handler = new WeakHandler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {

            switch (msg.what) {
                case 0:
                    Logger.ds("update handler");
                    ToastUtils.showToast("修改成功!");
                    sbUpdate.setVisibility(View.GONE);
                    isInterrupt = true;
                    break;
                case 1:
                    Logger.ds("delete handler");
                    ToastUtils.showToast("删除成功!");
                    sbUpdate.setVisibility(View.GONE);
                    //isInterrupt = true;
                    break;
            }

            //不需要继续处理msg了
            return true;
        }
    });


}
